package com.runshu.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

/**
 * json工具类
 *
 * @author zxy
 * @date 2020-05-02
 */
public class JsonUtils {

    public static String toJson(Object obj) {
        ObjectMapper om = new ObjectMapper();
        StringWriter sw = new StringWriter();
        try {
            om.writeValue(sw, obj);
            return sw.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                sw.close();
            } catch (IOException ignored) {
            }
        }
        return null;
    }

    public static <T> T toObject(String data, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        try {
            return om.readValue(data, clazz);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("json  解析出错：" + data);
        }
        return null;
    }

    public static <T> T toObject(String data, TypeReference<T> tr) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            if (org.apache.commons.lang3.StringUtils.isBlank(data)) {
                return null;
            }
            return objectMapper.readValue(data, tr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description: 忽略注解
     *
     * @author Don
     * @date 2017-07-07 19:13:39
     */
    public static <T> T toObjectIgnoreAnn(String data, Class<T> clazz) {
        ObjectMapper om = new ObjectMapper();
        om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        om.configure(MapperFeature.USE_ANNOTATIONS, false);
        try {
            return om.readValue(data, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description: 忽略注解
     *
     * @author Don
     * @date 2017-07-07 19:13:17
     */
    public static <T> T toObjectIgnoreAnn(String data, TypeReference<T> tr) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        try {
            return objectMapper.readValue(data, tr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
